from django.shortcuts import render, redirect
# 导包
from rest_framework.response import Response
from rest_framework.views import APIView
import time

from .models import *
import requests
import json
import hmac
import base64
from hashlib import sha256
import urllib


# 构造钉钉回调方法
def dingBack(request):
    # 获取code
    code = request.GET.get("code")
    print(code)

    t = time.time()
    # 时间戳
    timestamp = str((int(round(t * 1000))))
    appSecret = 'KcABdDAOBuiUMI7VRftnqTrI1q3CvOeAG4Qnlu4fcYuGbgWaFDIhbz1wqhSgfH-N'
    # 构造签名
    signature = base64.b64encode(
        hmac.new(appSecret.encode('utf-8'), timestamp.encode('utf-8'), digestmod=sha256).digest())
    # 请求接口，换取钉钉用户名
    payload = {'tmp_auth_code': code}
    headers = {'Content-Type': 'application/json'}
    res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature=' + urllib.parse.quote(
        signature.decode("utf-8")) + "&timestamp=" + timestamp + "&accessKey=dingoawcbhhfj9bdsvwprj",
                        data=json.dumps(payload), headers=headers)

    res_ = json.loads(res.text)
    name = res_['user_info']['nick']
    # 判断用户是否登陆过
    user = User.objects.filter(username=str(name)).first()
    if user:
        ding_id = user.username
        uid = user.id
    else:
        # 手动创建账号
        User.objects.create(username=str(name), password='')
        user = User.objects.filter(username=str(name)).first()
        ding_id = user.username
        uid = user.id
    print(ding_id, uid)
    return redirect('http://localhost:8080?sina_id=' + ding_id + '&uid=' + str(uid))


# 注册视图
class Reg_zk(APIView):

    def get(self, request):
        username = request.GET.get('username')
        password = request.GET.get('password')
        print(username, password)
        if not all([username, password]):
            return Response({
                'code': 10008,
                'data': '数据信息不完整'
            })
        else:
            user = User.objects.filter(username=username).first()
            if user:
                return Response({
                    'code': 10009,
                    'data': '该用户名已存在，不可重复注册'
                })
            else:
                User.objects.create(username=username, password=password)
                return Response({
                    'code': 200,
                    'data': '注册成功'
                })


# 登录视图
class Login_zk(APIView):

    def get(self, request):
        username = request.GET.get('username')
        password = request.GET.get('password')
        print(username, password)
        user = User.objects.filter(username=username, password=password).first()
        if user:
            return Response({
                'code': 200,
                'message': '登录成功',
                'username': user.username,
                'uid': user.id
            })
        else:
            return Response({
                'code': 10010,
                'message': '用户名或密码输入错误'
            })

